//
//  MySearchViewController.m
//  Toyohu
//
//  Created by celia on 16/3/31.
//  Copyright (c) 2016年 celia. All rights reserved.
//

#import "MySearchViewController.h"
#import "HJTTokenManager.h"
#import "HistoeyTableViewCell.h"
#import "SearchDetailViewController.h"
#import "HistoryTitleTableViewCell.h"
// 标签云
#import "BtnView.h"
#import "masonry.h"
#import "ReloadButton.h"
#import "ReloadButtonModel.h"
#import "MacroDefinition.h"


#import "TECustomTextField.h"
#import "GPAFNetworking3.h"

//#import "TECustomTextField.h"
#import "GPSearchBar.h"
#import "GPCustomMD.h"
#import "SearchViewModel.h"


#define WIDTH self.view.bounds.size.width
#define HEIGHT self.view.bounds.size.height
#define fontCOLOR [UIColor colorWithRed:163/255.0f green:163/255.0f blue:163/255.0f alpha:1]


static NSString *HistoeyReuseId = @"HistoeyTableViewCell";
static NSString *HistoeyTitleReuseId = @"HistoryTitleTableViewCell";

@interface MySearchViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    UITextField *searchTextField;
    UILabel *hotLabel;
    NSMutableArray *ary;
    
    UIView *_tagView;
}

@property (nonatomic,strong) UITableView * myTableView;

@property (nonatomic,strong)NSMutableArray * searchHistory;
//搜索记录的数组
@property (nonatomic,strong)NSMutableArray *myArray;

@end

@implementation MySearchViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:NO];
    [self readNSUserDefaults];
   
    self.navigationController.navigationBar.hidden = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBar.hidden = NO;
    self.view.backgroundColor =[UIColor colorWithRed:236/255.0 green:236/255.0 blue:236/255.0 alpha:1];
    
    ary = [NSMutableArray arrayWithObjects:@"回复非常及时、满意",@"意见很有帮助",@"非常认真敬业",@"非常清楚",@"回复非常及时、满意",@"由衷的感谢您老师", nil];
    //初始化数组
    _searchHistory = [NSMutableArray array];
   
    
    hotLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, 64, WIDTH/3, 40)];
    
    hotLabel.text = @"热门标签";
    hotLabel.backgroundColor = [UIColor colorWithRed:236/255.0 green:236/255.0 blue:236/255.0 alpha:1];
    hotLabel.textColor = [UIColor colorWithRed:128/255.0 green:128/255.0 blue:128/255.0 alpha:1];
    hotLabel.textAlignment = NSTextAlignmentNatural;
    [self.view addSubview:hotLabel];
    
     ReloadButton*reloadButton = [[ReloadButton alloc] init];
     ReloadButtonModel*model = [ReloadButtonModel modelWithName:@"换一组" icon:@"change@2x"];
    reloadButton.model = model;
    [self.view addSubview:reloadButton];
    [reloadButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(self.view.mas_trailing);
        make.centerY.equalTo(hotLabel.mas_centerY);
        make.width.equalTo(@80);
        make.height.equalTo(@45);
    }];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(getTags)];
    [reloadButton addGestureRecognizer:tap];
    
    //导航栏左边项
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeSystem];
    rightButton.frame = CGRectMake(0, 0, 40, 25);
    [rightButton setTitle:@"取消" forState:UIControlStateNormal];
    [rightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    rightButton.titleLabel.font = [UIFont systemFontOfSize: 17.0];
    [rightButton addTarget:self action:@selector(goBackPreviousPage) forControlEvents:UIControlEventTouchDown];
    UIBarButtonItem *rightNavItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = rightNavItem;
    
    UIView *zeroView = [[UIView alloc]initWithFrame:CGRectZero];
    UIBarButtonItem *leftNavItem = [[UIBarButtonItem alloc]initWithCustomView:zeroView];
    self.navigationItem.leftBarButtonItem = leftNavItem;
    
    

    //创建UITableView
    self.myTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 104+(ary.count/3)*80, WIDTH, HEIGHT-104-(ary.count/3)*80) style:UITableViewStylePlain];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.myTableView.estimatedRowHeight = 4.0f;
    self.myTableView.rowHeight = UITableViewAutomaticDimension;
    self.myTableView.tableFooterView = [UIView new];
    self.myTableView.backgroundColor = RGB(237, 238, 231);
    self.myTableView.separatorColor = [UIColor clearColor];
    
    [self.view addSubview:self.myTableView];
    
    [_myTableView registerNib:[UINib nibWithNibName:@"HistoeyTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:HistoeyReuseId];
    [_myTableView registerNib:[UINib nibWithNibName:@"HistoryTitleTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:HistoeyTitleReuseId];
    
    [self initTagView];
    [self initSearchBar];
    
    [self  getTags];
}

- (void)getTags
{
    WS
    [SearchViewModel getTagName:^(NSArray *tagNameArray) {
        SS
        [strongSelf change:tagNameArray];
    } tags:^(NSArray *tagsArray) {
        
    } error:^(NSString *error) {
        
    }];
} 

- (void)initSearchBar
{
    WS
    GPSearchBar *searchBar = [[GPSearchBar alloc] initWithPlaceholder:@"搜索话题或专家" frame:CGRectMake(0, 0, 4*WIDTH/5, 40) search:^(NSString *str) {
        if (str.length > 0) {
            SS
            [HJTTokenManager SearchText:str];//缓存搜索记录
            [strongSelf readNSUserDefaults];
//            [searchBar.searchBar resignFirstResponder];
            //宝宝、脾气、不合群
            SearchDetailViewController *SearchVC = [[SearchDetailViewController alloc]init];
            SearchVC.searchStr = str;
            [self.navigationController showViewController:SearchVC sender:nil];
        }else{
            
        }
    }];
    
    searchBar.tag = 101;
    searchBar.backgroundColor = [UIColor clearColor];
    self.navigationItem.titleView = searchBar;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [((GPSearchBar*)self.navigationItem.titleView).searchBar  resignFirstResponder];
}

- (void)initTagView
{
    _tagView = [BtnView creatBtnAndinterestingArray:ary];
    for (UIButton *btn in _tagView.subviews) {
        [btn addTarget:self action:@selector(handleButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    [self.view addSubview:_tagView];
}

-(void)change:(NSArray *)array
{
    ary = [array mutableCopy];
    [self initTagView];
    
}


//标签云 相应的点击事件
- (void)handleButton:(UIButton *)button{
    button.selected = !button.selected;
    if (button.selected) {
        button.backgroundColor = [UIColor colorWithRed:120/255.0 green:28/255.0 blue:161/255.0 alpha:1];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        SearchDetailViewController *SearchVC = [[SearchDetailViewController alloc]init];

        
        SearchVC.searchStr = button.titleLabel.text;

        [self.navigationController showViewController:SearchVC sender:nil];

        
    }else{
        
        button.backgroundColor = [UIColor whiteColor];
        [button setTitleColor:[UIColor purpleColor] forState:UIControlStateNormal];
        button.layer.borderWidth = 1;
        button.layer.borderColor = [UIColor purpleColor].CGColor;
    }
}

-(void)goBackPreviousPage{
    
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



#pragma mark --UITableViewDelegate  DataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
        if (_myArray.count>0) {
            return _myArray.count+1+1;
        }else{
            return 1;
        }
    
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  
        if(indexPath.row ==0){
            
            _myTableView.rowHeight=44;
            HistoryTitleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:HistoeyTitleReuseId];
            if (!cell) {
                cell = (HistoryTitleTableViewCell *)[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier: HistoeyTitleReuseId];
            }
            return cell;
            
            
        }else if (indexPath.row == _myArray.count+1){
            UITableViewCell * cell = [[UITableViewCell alloc] initWithStyle:0 reuseIdentifier:@"cell"];
            cell.textLabel.text = @"清除历史记录";
            cell.textLabel.textColor = fontCOLOR;
            cell.textLabel.textAlignment = NSTextAlignmentCenter;
            return cell;
        }else{
          
            _myTableView.rowHeight=50;
            HistoeyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:HistoeyReuseId];
            if (!cell) {
                cell = (HistoeyTableViewCell *)[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier: HistoeyReuseId];
            }
            NSArray* reversedArray = [[_myArray reverseObjectEnumerator] allObjects];
            cell.title.text = reversedArray[indexPath.row-1];
            cell.historyImg.image = [UIImage imageNamed:@"clock@2x"];
            cell.deleteButton.tag = indexPath.row;
            [cell.deleteButton addTarget:self action:@selector(deleteColum:) forControlEvents:UIControlEventTouchUpInside];
            return cell;
        }
    
}

-(void)deleteColum:(UIButton *)button
{
    
    [HJTTokenManager removeArrayObjectAtIndex:button.tag - 1];//缓存搜索记录
    [self readNSUserDefaults];
//    [_myTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:button.tag - 1 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
    [_myTableView reloadData];
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.myTableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == _myArray.count+1) {//清除所有历史记录
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"清除历史记录" message:@"" preferredStyle: UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *deleteAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction *  action) {
            [HJTTokenManager removeAllArray];
            _myArray = nil;
            [self.myTableView reloadData];
        }];
        
        [alertController addAction:cancelAction];
        [alertController addAction:deleteAction];
       
        [self presentViewController:alertController animated:YES completion:nil];
    }else{
        HistoeyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:HistoeyReuseId];
        if (!cell) {
            cell = (HistoeyTableViewCell *)[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier: HistoeyReuseId];
        }
        NSArray* reversedArray = [[_myArray reverseObjectEnumerator] allObjects];
        cell.title.text = reversedArray[indexPath.row-1];
        SearchDetailViewController *SearchVC = [[SearchDetailViewController alloc]init];
        SearchVC.searchStr = cell.title.text;
        [self.navigationController pushViewController:SearchVC animated:YES];
    }
}

/**
 *  取出缓存的数据
 */
-(void)readNSUserDefaults{
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    //读取数组NSArray类型的数据
    NSMutableArray * myArray = (NSMutableArray *)[userDefaultes arrayForKey:@"myArray"];
    self.myArray = myArray;
    [self.myTableView reloadData];

}






@end
